﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Xml.Serialization;
using TestLogMonitor.Helper;
using TestLogMonitor.Model;

namespace TestLogMonitor.Common
{
    public class BusinessProcess
    {
        static SqlHelper sqlHelper = new SqlHelper();
        /// <summary>
        /// 序列化XML文件
        /// </summary>
        /// <param name="path">the path to save the xml file</param>
        /// <param name="obj">the object you want to serialize</param>
        public static void SerializeToXml<T>(string path, T obj) where T : class
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(obj.GetType());
                string content = string.Empty;
                //serialize
                using (StringWriter writer = new StringWriter())
                {
                    serializer.Serialize(writer, obj);
                    content = writer.ToString();
                }
                //save to file
                using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
                {
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        sw.Write(content);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
            }
           
        }

        /// <summary>
        /// 反序列XML文件
        /// </summary>
        /// <param name="path">the path of the xml file</param>
        /// <param name="object_type">the object type you want to deserialize</param>
        public static T DeserializeFromXml<T>(string path) where T : class
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                using (StreamReader reader = new StreamReader(path))
                {
                    return serializer.Deserialize(reader) as T;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
                return null;
            }
        
        }
        public static bool SaveTestLog(SqlResultEntity entity)
        {
            StringBuilder sql = new StringBuilder();
            try
            {
                sql.AppendFormat("insert into testlog ([Filename],ChipID,QR,Result,Error,Time,Other,Uploadtime) " +
                    "values('','','{0}','{1}','','{2}','{3}','{4}')",
                    entity.QRCode, 
                    entity.Result.Substring(0,1).ToUpper()+entity.Result.Substring(1).ToLower(),
                    DateTime.Now.ToString("yyyyMMddHHmmss"),
                    entity.Operator??"",
                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                SqlHelper sqlHelper = new SqlHelper();
                return sqlHelper.ExecuteNonQuery(sql.ToString());
            } 
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
                return false;
            }  
        }
        public static bool SaveTestTracking(SqlResultEntity entity)
        {
            string retMsg = string.Empty;//返回的结果信息
            SqlParameter[] sqlParameters = null;
            try
            {
                sqlParameters = new SqlParameter[]
                {
                new SqlParameter("@QRCode",SqlDbType.NVarChar,200),
                new SqlParameter("@ChipID",SqlDbType.NVarChar,200),
                new SqlParameter("@Station",SqlDbType.NVarChar,200),
                new SqlParameter("@FailValue",SqlDbType.NVarChar,200),
                new SqlParameter("@FailDesc",SqlDbType.VarChar,1000),
                new SqlParameter("@Result",SqlDbType.NVarChar,200),
                new SqlParameter("@Time",SqlDbType.NVarChar,200),
                new SqlParameter("@Other",SqlDbType.NVarChar,1000),
                new SqlParameter("@Operator",SqlDbType.NVarChar,50),
                new SqlParameter("@TestMachine",SqlDbType.NVarChar,50),
                new SqlParameter("@FileName",SqlDbType.NVarChar,200),
                new SqlParameter("@StateCode",SqlDbType.NVarChar,1),
                new SqlParameter("@StateMsg",SqlDbType.NVarChar,1000),
                };
                sqlParameters[0].Value = entity.QRCode??"";
                sqlParameters[1].Value = entity.ChipID??"";
                sqlParameters[2].Value = entity.Station??"";
                sqlParameters[3].Value = entity.FailValue??"";
                sqlParameters[4].Value = entity.FailDesc??"";
                sqlParameters[5].Value = entity.Result??"N/A";
                sqlParameters[6].Value = entity.Time??"";
                sqlParameters[7].Value = entity.Other??"";
                sqlParameters[8].Value = entity.Operator??"";
                sqlParameters[9].Value = entity.TestMachine??"";
                sqlParameters[10].Value = entity.FileName ?? "";
                sqlParameters[11].Direction = ParameterDirection.Output;
                sqlParameters[12].Direction = ParameterDirection.Output;
                retMsg = sqlHelper.ExecuteStoredProcedure("procSaveTestTracking", sqlParameters);
                if (retMsg.Split('|')[0] != "1")
                    return false;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
                return false;
            }
            return true;
        }
        /// <summary>
        /// 转换字符串时间格式为Datetime格式
        /// </summary>
        /// <param name="strDatetime">字符串时间格式</param>
        /// <param name="format">时间格式</param>
        /// <returns></returns>
        public static DateTime ConvertDatetime(string strDatetime)
        {
            //240823111701
            if (strDatetime.Length == 12)
            {
                if (DateTime.TryParseExact(strDatetime, "yyMMddHHmmss", null, System.Globalization.DateTimeStyles.None, out DateTime dateTime))
                {
                    return dateTime;
                }
            }
            //20240823111701
            else if (strDatetime.Length == 14)
            {
                if (DateTime.TryParseExact(strDatetime, "yyyyMMddHHmmss", null, System.Globalization.DateTimeStyles.None, out DateTime dateTime))
                {
                    return dateTime;
                }
            }
          
            return DateTime.MinValue;
        }
    }
}
